/**
 * API路由文件
 */
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const router = express.Router();
const {
  saveReview,
  fetchReviews,
  fetchCount,
  fetchModeStat,
} = require("../utils/dbService");
const config = require("../config");
const { CozeAPI, COZE_CN_BASE_URL } = require("@coze/api");
const { loggers } = require('winston');
const { uploaderProps } = require('vant');
const { formatDate } = require('../utils/dateUtils');

// 健康检查路由
router.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// 练习相关路由
router.post('/practice/submit', (req, res) => {
  let answer = `问题：${req.body.title} 
  描述：${req.body.description}
  回答：${req.body.text}`;
  let parameters = { input: answer, type: "feedback" };
  // Import token using the environment variable
  const token = config.app.coze.cozeApiToken || "input your coze api token";
  // Create a client instance
  const client = new CozeAPI({
    baseURL: config.app.coze.cozeCnBaseURL,
    token: token,
  });
  client.workflows.runs.create({
      workflow_id: "7481605744376250418",
      parameters: parameters,
    })
    .then(async (resp) => {
      if (resp.code == 0) {
        let data = JSON.parse(resp.data)["output"][0];
        data.questionId = req.body.questionId;
        // questionId, question, answer, score, review, createdAt, updatedAt
        saveReview({
          ...data,
          ...{
            question: `${req.body.title}描述：${req.body.description}`,
            answer: `${req.body.text}`,
            mode: req.body.mode,
            createdAt: formatDate(),
            updatedAt: formatDate(),
          },
        });
        res.json({
          success: true,
          data: data,
        });
      } else {
        loggers.error(resp);
        res.json({
          success: false,
          data: null,
        });
      }
    });
});

// 题目相关路由
router.get('/questions', (req, res) => {
  const mode = req.query.mode || 'daily';
  let parameters = {"input": mode}
  // Import token using the environment variable
  const token = config.app.coze.cozeApiToken || "input your coze api token";
  console.log(token);
  // Create a client instance
  const client = new CozeAPI({
    baseURL: config.app.coze.cozeCnBaseURL,
    token: token,
  });
  client.workflows.runs.create({
    workflow_id: "7481605744376250418",
    parameters: parameters,
  }).then((resp) => {
    if (resp.code == 0) {
      let data = JSON.parse(resp.data)["output"][0];
      data.questionId = uuidv4();
      res.json({
        success: true,
        data: data,
      });
    } else {
      loggers.error(resp);
      res.json({
        success: false,
        data: null
      })
    }
  });
});
router.get("/practice/history", (req, res) => {
  // 从数据库中获取评测结果
  const response = fetchReviews();
  let data = {
    date: [],
    score: [],
  }
  response.then( (resp) => {
    for (let i = resp.length - 1; i >= 0; i--) {
      const element = resp[i];
      data.date.push(element.createdAt.split(" ")[0]);
      data.score.push(element.score);
    }
    res.json({
      success: true,
      data: data,
    });
  })
});
router.get("/practice/total", (req, res) => {
  // 从数据库中获取评测结果
  const response = fetchCount();
  response.then((resp) => {
    res.json({
      success: true,
      data: resp,
    });
  });
});

router.get("/practice/stat", (req, res) => {
  // 从数据库中获取评测结果
  const response = fetchModeStat();
  response.then((resp) => {
    res.json({
      success: true,
      data: resp,
    });
  });
});
module.exports = router;